package com.ruoyi.system.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.Dto.DrawingData;
import com.ruoyi.system.Dto.StrokeData;
import com.ruoyi.system.constant.Constants;
import com.ruoyi.system.domain.ScrTotal;
import com.ruoyi.system.service.IScaleService;
import com.ruoyi.system.service.IScrTotalService;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.implementation.bind.annotation.Origin;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ScaleRecord;
import com.ruoyi.system.service.IScaleRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@RestController
@RequestMapping("/scale")
public class ScaleRecordController extends BaseController
{
    private static final String UPLOAD_DIR = "C:\\qhq_proj\\upload_files"; // 你的上传目录路径
    @Autowired
    private IScaleRecordService scaleRecordService;

    @Autowired
    private IScrTotalService scrTotalService;

    @Autowired
    private IScaleService scaleService;

    private static String convertListToJson(List<List<StrokeData>> data) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/insertscale")
    public AjaxResult insertscale(@RequestBody DrawingData drawingData){
        logger.info("drawingData: {}", drawingData);
        ScaleRecord scaleRecord = new ScaleRecord();
        scaleRecord.setJson(convertListToJson(drawingData.getJson()));
        scaleRecord.setTim(drawingData.getTim());
        scaleRecord.setPenId(drawingData.getPenId());
        scaleRecord.setTimeStamp(drawingData.getTimeStamp());
        scaleRecordService.insertScalerecordcomplex(scaleRecord);
        return AjaxResult.success(scaleRecord.getId());
    }

    @PostMapping("/updatescale")
    public AjaxResult updatescale(@RequestBody ScrTotal scrTotal){
        return toAjax(scrTotalService.updateScrTotalbyscrid(scrTotal));
    }

    @GetMapping("/testmmse")
    public AjaxResult testmmse(){
        return new AjaxResult(100,"success");
    }


    @PostMapping("/getscale")
    public AjaxResult getscale(@RequestBody ScaleRecord scaleRecord){
        ScaleRecord scaleRecord1 = scaleRecordService.selectScaleRecordById(scaleRecord.getId());
        if(scaleRecord1.getStatus()==0||scaleRecord1.getStatus()==1)
            return AjaxResult.error("处理数据中，请等待"); //返回500
        else{
            ScrTotal scrTotal = new ScrTotal();
            scrTotal.setScrId(scaleRecord.getId());
            List<ScrTotal> list = scrTotalService.selectScrTotalList(scrTotal);
            return AjaxResult.success(list.get(0)); //返回200状态
        }
    }

    @PostMapping("/upload_sound")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("No file uploaded");
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 确保上传目录存在
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 创建文件的完整路径
            File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);

            // 使用 BufferedOutputStream 将文件写入到服务器
            try (BufferedOutputStream stream = new BufferedOutputStream(Files.newOutputStream(serverFile.toPath()))) {
                byte[] bytes = file.getBytes();
                stream.write(bytes);
            }
            assert fileName != null;
            AudioConverter.convertPcmToMp3(serverFile.getPath(), "C:\\qhq_proj\\upload_files\\" + fileName.replace(".pcm", ".mp3"));

            // 返回成功响应
            return ResponseEntity.ok("File uploaded successfully: " + fileName);
        } catch (IOException e) {
            // 处理异常情况
            return ResponseEntity.internalServerError().body("Could not upload the file: " + e.getMessage());
        }
    }
    @GetMapping("/img/{dir}/{name}")
    public void download(HttpServletResponse response, @PathVariable String name, @PathVariable String dir){
        String basePath = Constants.BASE_DIR;
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + dir + "/" + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/png");
            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
